import os
from typing import Annotated

import httpx
from langchain_core.tools import tool


@tool
def get_static_map(
    location: Annotated[str, "中心点坐标。规则：经度和纬度用','分隔 经纬度小数点后不得超过6位。"],
    zoom: Annotated[int, "地图缩放级别,范围:从大到小为1-17"] = 12,
) -> str:
    """返回一张坐标点周围的地图图片"""

    amap_key = os.getenv("AMAP_API_KEY")

    base_url = r"https://restapi.amap.com/v3/staticmap"
    params = {"key": amap_key, "location": location, "zoom": zoom}

    response = httpx.get(base_url, params=params)

    try:
        if (r := response.json())["status"] == "0":
            error_msg = f"获取以下地图失败：{location}。错误信息: {r['info']}。"
            return error_msg

    except Exception:
        pass

    img_data = response.content

    file_name = location.replace(".", "_").replace(",", "_") + ".png"
    file_path = os.path.join(os.getcwd(), "static\\map_pngs", file_name)

    with open(file_path, "wb") as f:
        f.write(img_data)

    return file_name


if __name__ == "__main__":
    from dotenv import find_dotenv, load_dotenv

    _ = load_dotenv(find_dotenv())
    print(get_static_map.invoke({"location": "114.401283,30.522052"}))
